﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Principal;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using TFSBugTracking.Web.Properties;

namespace TFSBugTracking.Web
{
    /// <summary>
    /// Default Page (file bug page)
    /// </summary>
    public partial class _Default : System.Web.UI.Page
    {
        private const string TFSREPROFIELD = "Microsoft.VSTS.TCM.ReproSteps";
        private const string TFSASSIGNEDTOFIELD = "Assigned To";
        private const string TFSPRIORITYFIELD = "Priority";

        /// <summary>
        /// populate the software product list with known apps from mapping
        /// </summary>
        /// <param name="sender">who</param>
        /// <param name="e">what</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                ImpersonatingTfsAdapter c = (this).GetSessionCore();
                foreach (ProjectBugMap projectBugMapping in c.BugMaps)
                    _Products.Items.Add(projectBugMapping.ProductName);
            }
            catch (Exception exception)
            {
                LogError(exception);
            }
        }

        private void LogError(Exception exception)
        {
#if DEBUG
            _tfsValidationError.Text = exception.ToString();
#else
                _tfsValidationError.Text = exception.Message;
#endif
            System.Diagnostics.Trace.TraceError(exception.ToString());
        }

        /// <summary>
        /// files the bug when validation succeeeds
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void _submitButton_Click(object sender, EventArgs e)
        {
            try
            {
                ImpersonatingTfsAdapter c = ((Page)this).GetSessionCore();

                //get current mapping from mapping setup (lookup by software product)
                var bugMapping = (from bm in c.BugMaps
                                  where bm.ProductName.Equals(_Products.SelectedValue)
                                  select bm).FirstOrDefault();

                //ask adapter for a new bug workitem from bug template
                var bug = c.GetBugTemplate(bugMapping.TfsProjectName);
                PopulateBugWithPageValues(bugMapping, bug);

                var result = bug.Validate();

                if (result.Count != 0)
                {
                    ReportValidationErrors(result);
                }
                else
                {
                    bug.Save();
                    ResetPageValues(bug);
                }
            }
            catch (Exception ex)
            {
                LogError(ex);

            }
        }

        private void ReportValidationErrors(ArrayList result)
        {
            _tfsValidationError.Text = Resources.BugFileNotValid + Environment.NewLine;
            foreach (object error in result)
                _tfsValidationError.Text += error.ToString() + Environment.NewLine;
        }

        private void ResetPageValues(WorkItem wi)
        {
            _tfsValidationError.Text = string.Format(Resources.IssueSavedToDB_UseIDXToFollowUpStatus, wi.Project.Name, wi.Id);
            _bugDescription.Text = string.Empty;
            _bugTitle.Text = string.Empty;
            _priorityRadioButtons.SelectedIndex = 0;
            _workaround.Text = string.Empty;
        }

        private void PopulateBugWithPageValues(ProjectBugMap bugMapping, WorkItem bug)
        {
            bug.AreaPath = bugMapping.TfsAreaPath;
            bug.IterationPath = bugMapping.TfsIterationPath;
            bug.Title = _bugTitle.Text;
            bug.Description = _bugDescription.Text + Environment.NewLine;
            //append workaround to description text (no special field in use)
            if (!string.IsNullOrEmpty(_workaround.Text))
                bug.Description += string.Format("<p>Workaround: {0}</p>", _workaround.Text);
            //for new tfs2010 agile 5.0 bug items the description is not visible but the repro steps
            if (bug.Fields.Contains(TFSREPROFIELD))
                bug.Fields[TFSREPROFIELD].Value = bug.Description;
            bug.Fields[TFSASSIGNEDTOFIELD].Value = bugMapping.TfsDefaultAssignTo;
            bug.Fields[TFSPRIORITYFIELD].Value = _priorityRadioButtons.SelectedIndex + 1;

        }
    }
}
